<!--
 * @Description:按钮组
          "Point":点
          "LineString":线
          "Polygon":多边形
          "Circle":圆
          "Box":长方形
          "Square":正方形
          "stop":退出编辑
          "empty":清空查询框
 * @Version: 2.0
 * @Author: zhao
 * @Date: 2022-06-17 09:12:17
 * @LastEditors: zhao
 * @LastEditTime: 2022-07-04 11:07:35
-->
<template>
    <div id="group">
        <!-- <div class="btn-group" @click="setDraphical('Point')">
            <el-tooltip class="item" effect="dark" content="绘制点" placement="top">
                <img src="@/assets/yuandian.png" alt="" />
            </el-tooltip>
        </div>
        <div class="btn-group" @click="setDraphical('LineString')">
            <el-tooltip class="item" effect="dark" content="绘制线" placement="top">
                <img src="@/assets/zhixian.png" alt="" />
            </el-tooltip>
        </div> -->
        <!-- <div class="btn-group" @click="setDraphical('Circle')">
            <el-tooltip class="item" effect="dark" content="绘制圆" placement="top">
                <img src="@/assets/yuan.png" alt="" />
            </el-tooltip>
        </div> -->
        <div class="btn-group" @click="setDraphical('Square')">
            <el-tooltip class="item" effect="dark" content="绘制正方形" placement="top">
                <img src="@/assets/juxing.png" alt="" />
            </el-tooltip>
        </div>
        <div class="btn-group" @click="setDraphical('Polygon')">
            <el-tooltip class="item" effect="dark" content="绘制多边形" placement="top">
                <img src="@/assets/duobianxing.png" alt="" />
            </el-tooltip>
        </div>
        <div class="btn-group" @click="setDraphical('search')">
            <el-tooltip class="item" effect="dark" content="双击查询" placement="top">
                <img src="@/assets/zhizhen.png" alt="" />
            </el-tooltip>
        </div>
        <div class="btn-group" @click="setDraphical('empty')">
            <el-tooltip class="item" effect="dark" content="清空地图" placement="top">
                <img src="@/assets/qingkong.png" alt="" />
            </el-tooltip>
        </div>
    </div>
</template>

<script>
import "ol/ol.css"
import { createRegularPolygon } from "ol/interaction/Draw"
import { Point, Polygon, LineString, Circle } from "ol/geom" // 点线面
import { Feature } from "ol"
import { Vector as VectorSource } from "ol/source"
import { getTransform } from "ol/proj"
import { Vector as VectorLayer } from "ol/layer" // 实例化一个矢量图层Vector作为绘制层
import { Style, Fill, Stroke, Circle as CircleStyle } from "ol/style"
import { Draw } from "ol/interaction"
import { fromExtent } from "ol/geom/Polygon"
export default {
    components: {},
    props: {
        map: Object,
    },
    data() {
        return {
            draw: null, // 绘图
            butMap: null,
            drawLayer: null, // 图层
            drawSource: null,
            GeomvectorLayer: null,
            isDblclick: false,

            workAreaLayer: null,
        }
    },
    watch: {
        "$store.state.map.map"(val) {
            this.butMap = val
            this.dblclick()
            this.init()
        },
        "$store.state.map.geometryData": {
            handler: function (val, oldVal) {
                val && this.addGeomSquare(val)
            },
            immediate: true,
            deep: true,
        },
    },
    mounted() {},
    methods: {
        init() {
            this.$store.state.map.drawSource = new VectorSource()
            this.drawLayer = new VectorLayer({
                source: this.$store.state.map.drawSource,
                style: new Style({
                    fill: new Fill({
                        color: "rgba(255, 255, 255, 0.2)",
                    }),
                    stroke: new Stroke({
                        color: "#ffcc33",
                        width: 2,
                    }),
                    image: new CircleStyle({
                        radius: 7,
                        fill: new Fill({
                            color: "#ffcc33",
                        }),
                    }),
                }),
            })

            this.butMap.addLayer(this.drawLayer)
        },
        // 绘制图形
        setDraphical(stype, maxPoints = null) {
            // this.butMap = this.butMap ? this.butMap : this.$store.getters["map/GET_MAP"]
            this.clearQueryCondition()

            var geometryFunction = null
            const theType = stype
            this.empty()
            this.delGeomSquare()
            if (stype === "stop") return this.endDraphical()
            if (stype === "empty") return

            if (this.draw !== undefined && this.draw != null) this.butMap.removeInteraction(this.draw)

            if (stype === "Box") {
                stype = "LineString"
                maxPoints = 2
                geometryFunction = function (coordinates, geometry) {
                    if (!geometry) {
                        // 多边形

                        geometry = new Polygon({})
                    }
                    var start = coordinates[0]
                    var end = coordinates[1]
                    geometry.setCoordinates([[start, [start[0], end[1]], end, [end[0], start[1]], start]])
                    return geometry
                }
            }
            if (stype === "Square") {
                //正方形
                stype = "Circle" //设置绘制类型为Circle
                //设置几何信息变更函数，即创建正方形
                geometryFunction = new createRegularPolygon(4)
            }

            if (stype == "search") return this.mpaClick()
            this.draw = new Draw({
                source: this.$store.state.map.drawSource,
                type: stype,
                geometryFunction: geometryFunction,
                maxPoints: maxPoints, // 最大点数
            })

            this.getCoordinatePoint(theType)
            this.butMap.addInteraction(this.draw)
        },
        // 获取坐标点
        getCoordinatePoint(stype) {
            this.draw.on("drawend", (e) => {
                switch (stype) {
                    case "Circle":
                        var center = e.feature.getGeometry().getCenter()
                        var radius = e.feature.getGeometry().getRadius()

                        break
                    case "Point":
                        var coordinates_Point = e.feature.getGeometry().getCoordinates()

                        break
                    case "Polygon":
                        var coordinates_Line = e.feature.getGeometry().getCoordinates()
                        var strs = []
                        coordinates_Line[0].map((e) => {
                            var data = { x: e[0], y: e[1] }
                            strs.push(data)
                        })
                        this.$store.state.map.geometryCoordinate = [strs]
                        break
                    default:
                        var coordinates_Polygon = e.feature.getGeometry().getCoordinates()
                        // console.log("🚀 ~ file: button_group.vue ~ line 184 ~ this.draw.on ~ coordinates_Polygon", coordinates_Polygon)
                        // var strs = ""
                        // for (var s = 0; s < coordinates_Polygon[0].length; s++) {
                        //     strs += coordinates_Polygon[0][s] + "\n"
                        // }
                        // console.log(strs)
                        var strs = []
                        coordinates_Polygon[0].map((e) => {
                            var data = { x: e[0], y: e[1] }
                            strs.push(data)
                        })
                        this.$store.state.map.geometryCoordinate = [strs]
                }
                this.endDraphical()
            })
        },
        // 结束绘制
        endDraphical() {
            this.butMap.removeInteraction(this.draw)
        },
        empty() {
            this.$store.state.map.drawSource && this.$store.state.map.drawSource.clear()
            this.$store.state.map.mapList = []
            this.$store.state.table.PaginationData.total = 0
            // this.butMap.removeLayer(this.drawLayer)
        },
        mpaClick() {
            if (this.isDblclick) return (this.isDblclick = false)
            this.isDblclick = true
            this.butMap.on("dblclick", (evt) => {
                this.geocode(evt.coordinate)
            })
        },
        async geocode(lonlat) {
            if (!this.isDblclick) return
            this.delGeomSquare()
            this.empty()
            const GeoCode = await this.$store.dispatch("map/getGeoCode", lonlat)

            if (GeoCode.status != 200) return this.$message.error(GeoCode.data.msg)

            const code = GeoCode.data.result.addressComponent
            let data = []

            let obj = {
                pageSize: this.$store.state.table.searchData.pageSize,
                pageIndex: this.$store.state.table.searchData.pageIndex,
                area: code.province + code.city + code.county,
                points: this.getAreaPoints(code.county_code.substring(3)),
            }
            let area = {
                area: {
                    area_number: code.county_code.substring(3),
                    name: code.county,
                },
            }
            data = await this.$store.dispatch("map/getResultFromPoints", obj)

            if (data.data.length <= 0) {
                area = {
                    city: {
                        area_number: code.city_code.substring(3),
                        name: code.city,
                    },
                }

                obj.area = code.province + code.city
                obj.points = this.getAreaPoints(code.city_code.substring(3))
                data = await this.$store.dispatch("map/getResultFromPoints", obj)
            }
            this.$store.state.table.PaginationData.total = data.count
            this.$store.state.table.searchData = obj
            data.data.map((e) => {
                e.LonLat = this.getCentralData(e.maxX, e.maxY, e.minX, e.minY)
            })
            this.$store.state.map.selectType = "dblclick"
            this.$store.state.map.form = area
            this.$store.state.map.mapList = data.data
        },
        //通过坐标 设置几何图形
        addGeomSquare(LngLatBounds) {
            this.delGeomSquare()
            this.empty()
            this.$store.state.map.geometryLayer = new VectorSource()
            //创建一个图层
            this.GeomvectorLayer = new VectorLayer({
                source: this.$store.state.map.geometryLayer,
            })
            // 将绘制层添加到地图容器中

            this.butMap.addLayer(this.GeomvectorLayer)

            // this.$store.state.map.markerLayer.setSource(this.$store.state.map.geometryLayer)

            var rectangle = new Feature({
                geometry: new Polygon(LngLatBounds),
            })
            rectangle.setStyle(
                new Style({
                    stroke: new Stroke({
                        color: "#ffcc33",
                        width: 4,
                    }),
                })
            )

            this.$store.state.map.geometryLayer.addFeatures([rectangle])

            // this.$store.commit("map/selfAdaptionZoom", this.GeomvectorLayer)
        },
        delGeomSquare() {
            this.$store.commit("map/empty")
        },
        //获取中心坐标
        getCentralData(oneLon, oneLat, twoLon, twoLat) {
            //oneLon：第一个点的经度；oneLat：第一个点的纬度；twoLon：第二个点的经度；twoLat：第二个点的纬度；
            let aLon = 0,
                aLat = 0
            let bLon = Number(oneLon) - Number(twoLon)
            let bLat = Number(oneLat) - Number(twoLat)
            //Math.abs()绝对值
            if (bLon > 0) {
                aLon = Number(oneLon) - Math.abs(bLon) / 2
            } else {
                aLon = Number(twoLon) - Math.abs(bLon) / 2
            }
            if (bLat > 0) {
                aLat = Number(oneLat) - Math.abs(bLat) / 2
            } else {
                aLat = Number(twoLat) - Math.abs(bLat) / 2
            }
            return [aLon, aLat]
        },
        //获取区域坐标
        getAreaPoints(code) {
            let jsonDATA = require("@/assets/json/" + code + ".json")
            let newdata = []
            let length = 0
            jsonDATA.features[0].geometry.coordinates.map((e, index) => {
                if (length == index) newdata[index] = new Array()
                length++

                e[0].map((s) => {
                    newdata[index].push({
                        x: s[0],
                        y: s[1],
                    })
                })
            })
            return newdata
        },
        //双击事件
        dblclick() {
            // this.butMap.on("dblclick", (evt) => {
            //     const coordinate = evt.coordinate // 获取坐标
            //     var pixel = this.butMap.getEventPixel(evt.originalEvent) //坐标
            //     this.feature = this.butMap.forEachFeatureAtPixel(pixel, (features, layer) => {
            //         if (features.values_.geometry instanceof Point) this.workArea(features.values_)
            //     })
            // })
        },
        workArea(data) {
            this.delGeomSquare()
            //实例化一个矢量图层Vector作为绘制层
            this.$store.state.map.workAreaSourceLayer = new VectorSource()
            //创建一个图层
            this.workAreaLayer = new VectorLayer({
                source: this.$store.state.map.workAreaSourceLayer,
            })
            // 将绘制层添加到地图容器中
            console.log("🚀 ~ file: button_group.vue:369 ~ workArea ~ this.workAreaLayer", this.workAreaLayer)
            this.butMap.addLayer(this.workAreaLayer)

            var rectangle = new Feature({
                geometry: new fromExtent([data.workAreaMaxX, data.workAreaMaxY, data.workAreaMinX, data.workAreaMinY]),
            })

            rectangle.setStyle(
                new Style({
                    fill: new Fill({
                        color: "rgba(33,33,33,0.5)",
                    }),
                    stroke: new Stroke({
                        color: "#ffcc33",
                        width: 4,
                    }),
                    image: new CircleStyle({
                        radius: 7,
                        fill: new Fill({
                            color: "#ffcc33",
                        }),
                    }),
                })
            )
            this.$store.state.map.workAreaSourceLayer.addFeatures([rectangle])

            this.$store.commit("map/selfAdaptionZoom", this.workAreaLayer)
        },
        //清空查询框
        clearQueryCondition() {
            this.$store.state.table.clearQueryCondition = true

            let time = setTimeout(() => {
                this.$store.state.table.clearQueryCondition = false
                clearTimeout(time)
            }, 500)
        },
    },
}
</script>

<style scoped lang="scss">
#group {
    .btn-group {
        margin: 0 5px;
        padding: 5px;
        display: inline-block;
        cursor: pointer;
        width: 35px;
        height: 35px;
        line-height: 30px;
        text-align: center;
        background: hsla(0, 0%, 100%, 0.92);
        -webkit-box-shadow: 0 0 4px 0 rgb(0 0 0 / 25%);
        box-shadow: 0 0 4px 0 rgb(0 0 0 / 25%);
        border-radius: 5px;

        img {
            width: 70%;
            height: 70%;
        }
    }
}
</style>
